package com.ibt.controller;

import java.io.IOException;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.ibt.dao.BugEntryDAO;
import com.ibt.dao.BuildIdsDAO;
import com.ibt.dao.ModuleDAO;
import com.ibt.dao.ProjectEntryDAO;
import com.ibt.entity.BugEntry;
import com.ibt.entity.BuildIds;
import com.ibt.entity.Business;
import com.ibt.entity.Login;
import com.ibt.entity.Module;
import com.ibt.entity.ProjectEntry;
import com.ibt.util.SendMail;

@Controller
@RequestMapping("/newbug")
public class NewBugController {
	@RequestMapping( "/show.do") 
	public ModelAndView insert(HttpServletRequest req,HttpSession session, ModelAndView model) throws Exception{
		Login  Ulogin=(Login)session.getAttribute("user");
		Business bus=(Business)session.getAttribute("business");
			ProjectEntryDAO oprD=new ProjectEntryDAO();
			List<ProjectEntry> opr=null;
			try{
				opr=(List<ProjectEntry>)oprD.findAll();
					System.out.println("opportunity list is "+opr);
			}catch(NullPointerException e){
				e.printStackTrace();
			}
			  model = new ModelAndView("/jsp/newbug.jsp");
				model.addObject("projectlist",opr);
				/*model.addObject("submenu", "sourcingInfo");
				model.addObject("menuName","sourcingInfo");*/
				return model;
	}
	@RequestMapping( "/showall.do") 
	public ModelAndView totalBugs(HttpServletRequest req,HttpSession session, ModelAndView model) throws Exception{
		Login  Ulogin=(Login)session.getAttribute("user");
		Business bus=(Business)session.getAttribute("business");
			List<BugEntry> buglist=null;
			buglist= BugEntryDAO.findAll(bus.getBusinessId());
			model.setViewName("/jsp/welcome.jsp");
			model.addObject("buglist",buglist);
				return model;
	}
	@RequestMapping("/showEdit.do")
	public @ResponseBody 
	String getUsers(HttpServletRequest req,HttpSession session) throws Exception {
		Login  Ulogin=(Login)session.getAttribute("user");
		Business bus=(Business)session.getAttribute("business");
		List<BugEntry> buglist=null;
		buglist= BugEntryDAO.findAll(bus.getBusinessId());
		System.out.println("buglist is "+buglist);
		Iterator<BugEntry> itr=buglist.iterator();
		StringBuffer sb=new StringBuffer();
		while(itr.hasNext()){
			Object obj=itr.next();
			BugEntry en=(BugEntry)obj;
			sb.append(en.getId()+"/"+en.getBugcode()+"("+en.getBugname()+")");		
		}
		return sb.toString();
	}
	@RequestMapping(value="/add.do",method = RequestMethod.POST)
	public ModelAndView userEntry(
			@RequestParam("pname") String pname, 
			@RequestParam("mname") String mname,
			@RequestParam("buildlist") String buildid,
			@RequestParam("odate") String odate, 
			@RequestParam("bcode") String bugcode,
			@RequestParam("ddate") String ddate,
			@RequestParam("platform") String platform,
			@RequestParam("bstatus") String bstatus,
			@RequestParam("bugpr") String bugpriority, 
			@RequestParam("bdesc") String bdesc,
			@RequestParam("sreprocheck") String stepsRepro,
			@RequestParam("stackcheck") String bstackcheck,
			ModelAndView model,HttpSession session,HttpServletRequest request) {
		if(stepsRepro!=null)
		{
			String steps=request.getParameter("steps"); 
		}
		byte[] stackTrace=null;
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file=null;
		if(bstackcheck!=null)
		{
			file = multipartRequest.getFile("stack");
		//	System.out.println("ContentType:" + file.getContentType());
			try {
				if(file!=null)
				{
				stackTrace=file.getBytes();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Login  Ulogin=(Login)session.getAttribute("user");
		Business bus=(Business)session.getAttribute("business");
		
		System.out.println("the session values are"+Ulogin+bus);
		/*StringBuffer str=multipartRequest.getRequestURL();*/
		
	/*	String str1=multipartRequest.getRealPath(lastName);*/
		 //String realPath = request.getRealPath(file);
		/* System.out.println("the real path is"+str);
		 System.out.println("the multipart path is"+str1);*/
		/*logger.info("File:" + file.getName());*/
		System.out.println("ContentType:" + file.getContentType());
		try {
			stackTrace=file.getBytes();
		} catch (IOException e) {
			e.printStackTrace();
		}
		BugEntry bEntry=new BugEntry();
		bEntry.setOpenDate(new java.util.Date());
		bEntry.setProjectName(pname);
		bEntry.setModuleName(mname);
		bEntry.setBuildId(buildid);
		bEntry.setBugcode(bugcode);
		bEntry.setBugname(bugcode);
		bEntry.setBusinessId(bus);
		bEntry.setReProduce(stepsRepro);
		bEntry.setDescription(bdesc);
		bEntry.setStackTrace(stackTrace);
		bEntry.setPriority(bugpriority);
		bEntry.setBugstatus(bstatus);
		bEntry.setPlatForm(platform);
		bEntry.setCreatedEname(Ulogin.getUserName());
		SendMail sm=new SendMail();
		/*String sourceName=request.getParameter("sourceName").trim();
		String refno=request.getParameter("refno").trim();*/
		Module mod=null;
		try {
			mod=ModuleDAO.getByName(pname,mname,bus.getBusinessId());
		} catch (Exception e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		ProjectEntry project=null;
		try {
			project=ProjectEntryDAO.getByName(pname,1);
		} catch (Exception e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		
		BuildIds build=null;
		try {
			 build= BuildIdsDAO.getUserByBuildName(buildid,project.getId(), mod.getId());
		} catch (Exception e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		
			System.out.println("the build developer name is"+build.getDeveloperName());
		 String mail=build.getDeveloperName();
		String from="bugtracker.mtech@gmail.com";
		System.out.println("User Email Id Is:"+from);
		String pass="btrack123";
		System.out.println("User password Is:"+pass);
		System.out.println("Email is:"+from+" Password is:"+pass);
		String soEmail="rajakmca09@gmail.com";
	
		String subject="New Bug With BugId : "+bugcode;
		StringBuilder body=new StringBuilder();
		body.append("Hello Dear, <br/>\n")
		.append("We Are Sorry To Say This Is New Bug in The Project/Module Name:"+pname+"<br/><br/> \n ")
		.append("Below Are The BugDetails Details.<br/> \n")
		.append(bugcode+"<br/>")
		.append("<br/>")
		.append(" Thanks & Regards <br/>\n \n")
		.append("Manager - Solutions <br/>\n \n ")
		.append("BugTracker"+" <br/> \n ");
	
	
	
		try {
			sm.sendMailNoFile(from,pass,body.toString(), subject, mail);
		} catch (AddressException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (MessagingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

     try {
		BugEntryDAO.insert(bEntry);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
		System.out.println("in x0029 searching  BusinessUserid " );
		model.setViewName("/jsp/newbug.jsp");
		model.addObject("msg","New Bug is Added to The Project with BugCode:"+bugcode);
		return model;

}
	@RequestMapping(value="/moduleSearch.do")
	public @ResponseBody  String moduleSearch ( 
			@RequestParam("pname") String projname,
			ModelAndView model,HttpSession session) throws Exception{
		Login  Ulogin=(Login)session.getAttribute("user");
		Business bus=(Business)session.getAttribute("business");
		StringBuilder modulelist=new StringBuilder();
		
	List<Module>  mlist= new ArrayList<Module>();

		StringBuilder sourcelist= new StringBuilder();
		
			mlist=ModuleDAO.getModuleList(projname.trim(),1);
		
		if (mlist!=null) {
			Iterator it = mlist.iterator();
			while (it.hasNext() == true) {
				Object ob = it.next();
				Module mod = (Module) ob;
				String qname = mod.getModuleName();
				sourcelist.append("," + qname);
			}
		}
		
		return sourcelist.toString();
     }
	@RequestMapping(value="/buildSearch.do")
	public @ResponseBody  String buildSearch ( 
			@RequestParam("pname") String projname,@RequestParam("mname") String modname,
			ModelAndView model,HttpSession session) throws Exception{
		
		Login  Ulogin=(Login)session.getAttribute("user");
		Business bus=(Business)session.getAttribute("business");
		StringBuilder namelist=new StringBuilder();
		
	List<BuildIds>  mlist= new ArrayList<BuildIds>();
		StringBuilder sourcelist= new StringBuilder();
		ProjectEntry project=ProjectEntryDAO.getByName(projname.trim(),bus.getBusinessId());
		Module modu=ModuleDAO.getByName(projname,modname, bus.getBusinessId());
	
			mlist=BuildIdsDAO.getBuildList(project.getId(),modu.getId(),bus.getBusinessId());
		
		if (mlist!=null) {
			Iterator it = mlist.iterator();
			while (it.hasNext() == true) {
				Object ob = it.next();
				BuildIds  build = (BuildIds) ob;
				String bnames = build.getBuildName();
				sourcelist.append("," + bnames);
			}
		}
		
		return sourcelist.toString();
     }
	
	@RequestMapping(value="/openBug.do",method = RequestMethod.GET)
	public ModelAndView getSrchEnq(HttpServletRequest req,HttpSession session, ModelAndView model) throws Exception{
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
		int busid=bus.getBusinessId();
		String refno=req.getParameter("refNo");
	int rno=Integer.parseInt(refno);
		BugEntry op=BugEntryDAO.getByRefNo(busid,rno);
		model.setViewName("/jsp/editbug.jsp");
		List<String> project=new ArrayList<String>();
		project.add(op.getProjectName());
		List<String> module=new ArrayList<String>();
		module.add(op.getModuleName());
		model.addObject("projectvalue",project);
		model.addObject("modulevalue",module);
		model.addObject("bugentry",op);
		return model;
		
	}
}
